"""
项目主入口文件
"""

import os
import time
import logging

from . import config
from .video_processing import (
    setup_environment,
    download_video,
    process_subtitles,
    burn_subtitles_and_finalize
)
from .ai_services import generate_ai_metadata
from .youtube_services import upload_to_youtube

def main():
    """执行完整的视频增强和上传流程"""
    start_time = time.time()
    
    # 1. 环境设置
    setup_environment()

    # 2. 下载视频
    original_video_path, base_name = download_video(config.VIDEO_URL)
    if not original_video_path:
        return

    knowledge_cards = []
    chapters = ""
    video_summary = ""
    video_keywords = []
    final_video_path = original_video_path
    bilingual_srt_path = None

    if config.USE_ORIGINAL_VIDEO_UNMODIFIED:
        logging.info("配置启用直接使用原视频，跳过字幕、AI 元数据与视频合成步骤。")
    else:
        if config.SKIP_SUBTITLE_PROCESSING:
            logging.info("配置为跳过字幕处理，将不执行自动识别与烧录。")
            full_text = ""
        else:
            full_text, bilingual_srt_path = process_subtitles(
                original_video_path, base_name, config.WORK_DIR
            )
            if not full_text or not bilingual_srt_path:
                return

            original_srt_path = os.path.join(config.WORK_DIR, f"{base_name}_original.srt")
            knowledge_cards, chapters, video_summary, video_keywords = generate_ai_metadata(
                full_text, original_srt_path, original_video_path
            )

        output_path = os.path.join(config.WORK_DIR, f"{base_name}_enhanced.mp4")
        burn_subtitles_and_finalize(
            original_video_path, bilingual_srt_path, knowledge_cards, output_path
        )
        final_video_path = output_path

    total_elapsed = time.time() - start_time
    if config.USE_ORIGINAL_VIDEO_UNMODIFIED:
        logging.info(f"--- 原视频上传准备完成，总用时: {total_elapsed:.2f} 秒 ---")
    else:
        logging.info(f"--- 视频处理完成，总用时: {total_elapsed:.2f} 秒 ---")

    # 6. 上传到 YouTube
    upload_to_youtube(final_video_path, base_name, chapters, video_summary, video_keywords)

if __name__ == "__main__":
    if not config.LLM_CLIENT:
        logging.error("LLM 客户端未初始化，无法执行。请在 config.py 中配置 API Key。")
    else:
        main()
